import { CommonModule } from '@angular/common';
import { Component, ComponentFactoryResolver, ComponentRef, Input, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { NgxRawTreeNodeActionComponent } from './ngx-raw-tree-node-action/ngx-raw-tree-node-action.component';


@Component({
  selector: 'lib-ngx-raw-tree-bar',
  standalone: true,
  imports: [CommonModule, FormsModule],
  // templateUrl: './ngx-raw-tree-bar.component.html',
  // styleUrl: './ngx-raw-tree-bar.component.css',
  styles: [
    `
      .tree-container {
        min-width: 300px;
        border: 1px solid #ccc;
        padding: 10px;
        border-radius: 4px;
      }
      .tree {
        list-style-type: none;
        padding-left: 20px;
      }
      .tree ul{
        list-style-type: none;
        padding-left: 20px;
      }
      .tree-item {
        cursor: pointer;
        margin: 5px 0;
        padding: 5px;
        border-radius: 4px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .tree-item.selected {
        background-color: orange;
        color: white;
      }
      .expand-icon {
        margin-right: 5px;
        font-weight: bold;
      }
      input[type="text"] {
        width: 100%;
        padding: 5px;
        margin-bottom: 10px;
        border: 1px solid #ccc;
        border-radius: 4px;
      }
      .actions {
        display: flex;
        gap: 5px;
      }
      .actions button {
        background-color: transparent;
        border: none;
        cursor: pointer;
        font-size: 12px;
        padding: 2px 5px;
        border-radius: 4px;
      }
      .actions button:hover {
        background-color: #ddd;
      }
    `,
  ],
  template: `
 <div class="tree-container">
      <input type="text" [(ngModel)]="searchQuery" placeholder="Search..." (input)="filterTree()" />
      <ul class="tree">
        <ng-container *ngFor="let item of filteredTreeData">
          <ng-container *ngTemplateOutlet="renderTreeItem; context: { $implicit: item }"></ng-container>
        </ng-container>
      </ul>
    </div>

    <ng-template #renderTreeItem let-item>
      <li>
      <div
          class="tree-item"
          [class.selected]="item.selected"
          (click)="selectItem(item, $event)"
        >
          <div>
            <span *ngIf="item.children?.length" class="expand-icon" (click)="toggleExpand(item,$event)">
              {{ item.expanded ? '-' : '+' }}
            </span>
            {{ item.name }}
          </div>
          <div class="actions">
            <button (click)="onAdd(item, $event)">Add</button>
            <button (click)="onEdit(item, $event)">Edit</button>
            <button (click)="onDelete(item, $event)">Delete</button>
          </div>
           
        </div>
        <ul *ngIf="item.expanded && item.children?.length">
          <ng-container *ngFor="let child of item.children">
            <ng-container *ngTemplateOutlet="renderTreeItem; context: { $implicit: child }"></ng-container>
          </ng-container>
        </ul>
      </li>
    </ng-template>
  `
})
export class NgxRawTreeBarComponent implements OnInit {
  @Input() treeData: TreeItem[] = [];

  ngOnInit() {
    this.assignParentReferences(this.treeData, null);
    this.filteredTreeData = this.treeData;
  }



  searchQuery: string = '';
  filteredTreeData: TreeItem[] = [];



  // 为每个节点分配父节点引用
  assignParentReferences(items: TreeItem[], parentId: number | null) {
    items.forEach(item => {
      // if (parent !== null) {
      //   item.parent = parent;
      // }
      item.parent = parentId;
      if (item.children) {
        this.assignParentReferences(item.children, item.id);
      }
    });
  }

  // 切换展开状态
  toggleExpand(item: TreeItem, event: Event) {
    event.stopPropagation();
    item.expanded = !item.expanded;
  }

  // 选中节点时，同时选中父节点
  selectItem(item: TreeItem, event: Event) {
    event.stopPropagation();
    this.clearSelection(this.treeData); // 清除之前选中的节点
    this.selectNodeWithParents(item);
  }

  // 递归选择节点并选中父节点
  selectNodeWithParents(item: TreeItem) {
    item.selected = true;
    const parentItem = this.findItemById(item.parent as number | null);
    if (parentItem) {
      this.selectNodeWithParents(parentItem);
    }
  }
  findItemById(id: number | null): TreeItem | undefined {
    const stack = [...this.treeData];
    while (stack.length) {
      const item = stack.pop();
      if (item && item.id === id) return item;
      if (item?.children) stack.push(...item.children);
    }
    return undefined;
  }

  // 清除所有节点的选中状态
  clearSelection(items: TreeItem[]) {
    items.forEach(item => {
      item.selected = false;
      if (item.children) {
        this.clearSelection(item.children);
      }
    });
  }

  // 过滤树形结构数据
  filterTree() {
    if (this.searchQuery) {
      this.filteredTreeData = this.filterTreeData(this.treeData, this.searchQuery.toLowerCase());
    } else {
      this.filteredTreeData = this.treeData;
    }
  }

  // 递归过滤树形结构数据
  filterTreeData(items: TreeItem[], query: string): TreeItem[] {
    return items
      .map(item => {
        const { children = [], ...itemWithoutChildren } = item;
        const filteredChildren = this.filterTreeData(children, query);

        if (item.name.toLowerCase().includes(query) || filteredChildren.length) {
          return {
            ...itemWithoutChildren,
            children: filteredChildren,
            expanded: filteredChildren.length > 0 || item.expanded,
          };
        }

        return null;
      })
      .filter(item => item !== null) as TreeItem[];
  }

  // Add a new child node
  onAdd(item: TreeItem, event: Event) {
    event.stopPropagation();
    // Logic for adding a new item as a child of the current item
    const newItem: TreeItem = {
      id: Date.now(), name: 'New Node',
      parent: item.id,
    };
    item.children = item.children || [];
    item.children.push(newItem);
    item.expanded = true; // Expand the node to show the new child
  }

  // Edit the current node
  onEdit(item: TreeItem, event: Event) {
    event.stopPropagation();
    // Logic for editing the current item
    const newName = prompt('Enter new name', item.name);
    if (newName) {
      item.name = newName;
    }
  }

  // Delete the current node
  onDelete(item: TreeItem, event: Event) {
    event.stopPropagation();
    // Logic for deleting the current item
    if (item.parent !== null) {
      const parentItem = this.findItemById(item.parent as number | null);
      if (parentItem) {
        parentItem.children = parentItem.children?.filter(child => child.id !== item.id);
      }
    } else {
      this.treeData = this.treeData.filter(treeItem => treeItem.id !== item.id);
      this.filteredTreeData = this.treeData;
    }
  }

}


export interface TreeItem {
  id: number;
  name: string;
  children?: TreeItem[];
  expanded?: boolean;
  selected?: boolean;  // 节点是否被选中
  parent?: number | null;   // 新增父节点引用
}